<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class DebugHelper
{
    /**
     * 调试信息输出
     *
     * @param mixed $data
     * @param string $label
     * @param string $channel
     */
    public static function debug($data, $label = 'DEBUG', $channel = 'debug')
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $caller = $trace[1] ?? [];
        
        $context = [
            'file' => $caller['file'] ?? 'unknown',
            'line' => $caller['line'] ?? 'unknown',
            'function' => $caller['function'] ?? 'unknown',
            'data' => $data
        ];
        
        Log::channel($channel)->debug("[$label] " . json_encode($context, JSON_UNESCAPED_UNICODE));
        
        // 如果是开发环境，同时输出到浏览器控制台
        if (app()->environment('local')) {
            static::browserConsole($data, $label);
        }
    }

    /**
     * 错误日志记录
     *
     * @param string $message
     * @param array $context
     */
    public static function error($message, $context = [])
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $caller = $trace[1] ?? [];
        
        $context = array_merge($context, [
            'file' => $caller['file'] ?? 'unknown',
            'line' => $caller['line'] ?? 'unknown',
            'function' => $caller['function'] ?? 'unknown',
        ]);
        
        Log::channel('error')->error($message, $context);
    }

    /**
     * 性能监控
     *
     * @param string $operation
     * @param callable $callback
     * @return mixed
     */
    public static function benchmark($operation, callable $callback)
    {
        $start = microtime(true);
        $startMemory = memory_get_usage();
        
        $result = $callback();
        
        $executionTime = round((microtime(true) - $start) * 1000, 2);
        $memoryUsage = round((memory_get_usage() - $startMemory) / 1024 / 1024, 2);
        
        Log::channel('performance')->info("Performance: $operation", [
            'execution_time_ms' => $executionTime,
            'memory_usage_mb' => $memoryUsage,
            'peak_memory_mb' => round(memory_get_peak_usage() / 1024 / 1024, 2)
        ]);
        
        return $result;
    }

    /**
     * SQL 查询监控
     */
    public static function enableQueryLogging()
    {
        DB::listen(function ($query) {
            Log::channel('query')->debug('SQL Query', [
                'sql' => $query->sql,
                'bindings' => $query->bindings,
                'time' => $query->time . 'ms'
            ]);
        });
    }

    /**
     * API 请求日志
     *
     * @param string $method
     * @param string $url
     * @param array $data
     * @param array $response
     */
    public static function apiLog($method, $url, $data = [], $response = [])
    {
        Log::channel('api')->info("API Call: $method $url", [
            'method' => $method,
            'url' => $url,
            'request_data' => $data,
            'response' => $response,
            'timestamp' => now()->toISOString()
        ]);
    }

    /**
     * 变量转储到文件
     *
     * @param mixed $data
     * @param string $filename
     */
    public static function dump($data, $filename = null)
    {
        $filename = $filename ?: 'dump_' . date('Y-m-d_H-i-s') . '.txt';
        $filepath = storage_path('logs/' . $filename);
        
        $content = "=== DUMP at " . now() . " ===\n";
        $content .= print_r($data, true);
        $content .= "\n=== END DUMP ===\n\n";
        
        file_put_contents($filepath, $content, FILE_APPEND | LOCK_EX);
        
        static::debug("Data dumped to: $filepath", 'DUMP');
    }

    /**
     * 浏览器控制台输出 (仅开发环境)
     *
     * @param mixed $data
     * @param string $label
     */
    protected static function browserConsole($data, $label = 'DEBUG')
    {
        static $scripts = [];
        
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        $script = "console.log('[PHP $label]:', $json);";
        
        if (!in_array($script, $scripts)) {
            $scripts[] = $script;
            
            if (!app()->runningInConsole()) {
                echo "<script>$script</script>";
            }
        }
    }

    /**
     * 调试栏信息收集
     *
     * @return array
     */
    public static function getDebugInfo()
    {
        return [
            'environment' => app()->environment(),
            'debug_mode' => config('app.debug'),
            'php_version' => PHP_VERSION,
            'laravel_version' => app()->version(),
            'memory_usage' => round(memory_get_usage() / 1024 / 1024, 2) . ' MB',
            'peak_memory' => round(memory_get_peak_usage() / 1024 / 1024, 2) . ' MB',
            'execution_time' => round((microtime(true) - LARAVEL_START) * 1000, 2) . ' ms',
            'included_files' => count(get_included_files()),
            'database_queries' => DB::getQueryLog(),
        ];
    }

    /**
     * 检查调试模式
     *
     * @return bool
     */
    public static function isDebugMode()
    {
        return config('app.debug', false);
    }

    /**
     * 条件调试 (仅在调试模式下执行)
     *
     * @param callable $callback
     */
    public static function when(callable $callback)
    {
        if (static::isDebugMode()) {
            $callback();
        }
    }
}